const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const base_url = "http://192.168.31.195:8083"
const encryptStr = 'ZHNsLXdlaXhpbndhOmRzbC13ZWl4aW53YV9zZWNyZXQ='

function httpGet(url, callback) {
  wx.request({
    url: base_url + url,
    header: {
      'Authorization': 'Basic ' + encryptStr
    },
    success: res => {
      if (res.statusCode == 200) {
        callback(res.data)
      }
    }
  })
}

function httpPost(url, data, callback) {
  wx.request({
    url: base_url + url,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + encryptStr
    },
    data: data,
    method: 'post',
    success: res => {
      if (res.statusCode == 200) {
        callback(res.data)
      }
    }
  })
}

function httpAuthGet(url, callback) {
  var access_grant = wx.getStorageSync("access_grant")
  var authorization = access_grant.token_type + " " + access_grant.access_token
  wx.request({
    url: base_url + url,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': authorization
    },
    success: res => {
      if (res.statusCode == 200) {
        callback(res.data)
      }
    }
  })
}

function httpAuthPost(url, data, callback) {
  var access_grant = wx.getStorageSync("access_grant")
  var authorization = access_grant.token_type + " " + access_grant.access_token
  wx.request({
    url: base_url + url,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': authorization
    },
    data: data,
    method: 'post',
    success: res => {
      if (res.statusCode == 200) {
        callback(res.data)
      }
    }
  })
}

function uploadFile(filePath, name='file') {
  console.log('upload')
  var access_grant = wx.getStorageSync("access_grant")
  var authorization = access_grant.token_type + " " + access_grant.access_token
  wx.uploadFile({
    url: base_url + '/api/upload',
    filePath: filePath,
    header: {
      'Authorization': authorization
    },
    name: name,
    success: function(res) {
      console.log(res)
    },
    fail: function(res) {
      console.log("error:" + res)
    }
  })
}


module.exports = {
  formatTime: formatTime,
  httpGet: httpGet,
  httpPost: httpPost,
  httpAuthGet: httpAuthGet,
  httpAuthPost: httpAuthPost,
  uploadFile: uploadFile
}
